//
//  SNSPhotoEditViewController.m
//  iBaby365v2
//
//  Created by Kirinrin on 14-8-13.
//  Copyright (c) 2014年 suplus. All rights reserved.
//

#import "SNSPhotoEditViewController.h"
#import "SNSMarkLabelView.h"
#import "SNSStickerView.h"
#import "EditPhotoMarkViewController.h"
#import "AppDelegate.h"
#import "NetworkAccessManager.h"
#import "UIAlertView+Kirinrin.h"
#import <UIProgressView+AFNetworking.h>

#define kAddMarkCell        @"AddMarkCell"
#define kStickersCell       @"StickersCell"
#define kFilterCell         @"FilterCell"

#define kSegueAddMark       @"toAddMarkView"

typedef enum PhotoEditCellType:NSUInteger{
    PhotoEditCellMark,
    PhotoEditCellStickers,
    PhotoEditCellFilter,
}PhotoEditCellType;

@interface SNSPhotoEditViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, EditPhotoMarkViewControllerDelegate, SNSMarkLabelViewDelegate, UIActionSheetDelegate>{
    
    SNSMarkLabelView *currentMarkLabelView;
}
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

@property (strong, nonatomic)NSArray *collectionData;

@property (weak, nonatomic) IBOutlet UIImageView *imageView;


@property (weak, nonatomic) IBOutlet UIView *markAndImageContainer;

@property (weak, nonatomic) IBOutlet UIView *imageContainerView;

@property (weak, nonatomic) IBOutlet UIProgressView *progressView;

@property (strong, nonatomic)NSMutableArray *stickerArray;
@end

@implementation SNSPhotoEditViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _collectionData = @[@{@"type": @(0)}, @{@"type": @(1), @"name":@"Stickers1"}, @{@"type": @(1), @"name":@"Stickers2"}, @{@"type": @(1), @"name":@"Stickers3"}, @{@"type": @(1), @"name":@"Stickers4"}, @{@"type": @(1), @"name":@"Stickers5"}, @{@"type": @(1), @"name":@"Stickers6"}, @{@"type": @(1), @"name":@"Stickers7"}, @{@"type": @(1), @"name":@"Stickers8"}, @{@"type": @(1), @"name":@"Stickers9"}, @{@"type": @(1), @"name":@"Stickers10"}, @{@"type": @(1), @"name":@"Stickers11"}];
    
    self.imageView.image = self.sourceImage;
//    [self addMarkView:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)addMarkView:(SNSMarkModel *)data{
    NSLog(@"%@", data.contentText);
    SNSMarkLabelView *mark = [[SNSMarkLabelView alloc]initWithDataModel:data];
    mark.delegate = self;
    [self.markAndImageContainer addSubview:mark];
    [self.markViewArray addObject:mark];
}

- (void)addStickerView:(NSDictionary *)data{
    SNSStickerView *sticker = [[SNSStickerView alloc]initWithImageName:data[@"name"]];
    [self.imageContainerView addSubview:sticker];
    [self.stickerArray addObject:sticker];
}

- (UIImage *)drawImage{
    CGRect frame = self.imageContainerView.frame;
    CGSize imageSize = CGSizeMake(frame.size.width, frame.size.height);
    UIGraphicsBeginImageContextWithOptions(imageSize, self.imageContainerView.opaque, [[UIScreen mainScreen] scale]);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [self.imageContainerView.layer renderInContext:context] ;
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:kSegueAddMark]) {
        EditPhotoMarkViewController *controller = (EditPhotoMarkViewController *)segue.destinationViewController;
        controller.delegate = self;
        if (sender) {
            controller.data = sender;
        }
    }
}


- (IBAction)sendPhotoAction:(id)sender {
    NSLog(@"sendPhotoMessages");
    
    UIImage *photo = [self drawImage];
    
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    NSString *uriString = @"Messages.json";
    NSDictionary *parameters = @{@"key": appDelegate.accessKey, @"photoMarker":[self markObjectArrayToJsonArray]};
    
    AFHTTPRequestOperation *uploadOpernation = [[NetworkAccessManager shareManager]POST:uriString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSData *photoData = UIImageJPEGRepresentation(photo, 1.0);
        NSData *preViewPhotoData = UIImageJPEGRepresentation(photo, 0.4);
        
        [formData appendPartWithFileData:photoData name:@"photo" fileName:[NSString stringWithFormat: @"%@.jpg",[[NSProcessInfo processInfo]globallyUniqueString]] mimeType:@"image/jpeg"];
        [formData appendPartWithFileData:preViewPhotoData name:@"photoPre" fileName:[NSString stringWithFormat:@"%@.jpg",[[NSProcessInfo processInfo]globallyUniqueString]] mimeType:@"image/jpeg"];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"opernation: %@\nresponse: %@", operation, responseObject);
        int resultCode = [responseObject[@"result"]intValue];
        if (resultCode == 0) {
            NSLog(@"图片上传成功!");
            
            [self dismissViewControllerAnimated:YES completion:NO];
            
            if (self.delegate) {
                [self.delegate didSendSNSPost];
            }
        }else{
            [UIAlertView alertWithFormCheckError:resultCode];
        }
        self.progressView.hidden = YES;
        self.view.userInteractionEnabled = YES;
        self.navigationController.view.userInteractionEnabled = YES;
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"opernation: %@\nerror: %@", operation, error);
        
        [UIAlertView alertWithNetworkError];
        self.progressView.hidden = YES;
        self.view.userInteractionEnabled = YES;
        self.navigationController.view.userInteractionEnabled = YES;
    }];
    [self.progressView setProgressWithUploadProgressOfOperation:uploadOpernation animated:YES];
    self.navigationController.view.userInteractionEnabled = NO;
    self.view.userInteractionEnabled = NO;
    self.progressView.hidden = NO;
    [self.view bringSubviewToFront:self.progressView];
}


#pragma mark - CollectionView

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.collectionData.count;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *cell;
    NSDictionary *data = self.collectionData[indexPath.item];
    switch ([data[@"type"]intValue]) {
        case PhotoEditCellMark:
            cell = [collectionView dequeueReusableCellWithReuseIdentifier:kAddMarkCell forIndexPath:indexPath];
            break;
        case PhotoEditCellStickers:
        {
            cell = [collectionView dequeueReusableCellWithReuseIdentifier:kStickersCell forIndexPath:indexPath];
            UIImageView *sticker = (UIImageView *)[cell viewWithTag:100];
            sticker.image = [UIImage imageNamed:data[@"name"]];
            NSLog(@"%@\t%@\t%@", NSStringFromCGRect(sticker.frame), NSStringFromCGRect(cell.frame), NSStringFromCGRect(cell.contentView.frame));
            break;
        }
        case PhotoEditCellFilter:
            cell = [collectionView dequeueReusableCellWithReuseIdentifier:kFilterCell forIndexPath:indexPath];
            break;
    }
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *data = self.collectionData[indexPath.item];
    
    CGSize cellSize;
    switch ([data[@"type"]intValue]) {
        case PhotoEditCellMark:
            cellSize = CGSizeMake(50, 88);
            break;
        case PhotoEditCellStickers:{
            UIImage *stickerImage = [UIImage imageNamed:data[@"name"]];
            CGSize imageSize = stickerImage.size;
            CGFloat scale = 88/imageSize.height;
            cellSize = CGSizeMake(imageSize.width*scale, 88);
        }
            break;
        case PhotoEditCellFilter:
            cellSize = CGSizeMake(76, 76);
            break;
    }
    
    return cellSize;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
//    NSLog(@"didSelectItemAtIndexPath %@", indexPath);
    NSDictionary *data = self.collectionData[indexPath.item];
    switch ([data[@"type"]intValue]) {
        case 0:
        {
            [self performSegueWithIdentifier:kSegueAddMark sender:nil];
            
        }
            break;
        case 1:
        {
            [self addStickerView:data];
            
        }
            break;
    }
    
}




#pragma mark - setter & getter
-(NSMutableArray *)markViewArray{
    if (!_markViewArray) {
        _markViewArray = [NSMutableArray array];
    }
    return _markViewArray;
}

-(NSMutableArray *)stickerArray{
    if(!_stickerArray){
        _stickerArray = [NSMutableArray array];
    }
    return _stickerArray;
}

-(NSString *)markObjectArrayToJsonArray{
    NSMutableArray *result = [NSMutableArray arrayWithCapacity:self.markViewArray.count];
    [self.markViewArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        SNSMarkLabelView *markView = obj;

        [result addObject:[markView toDictionary]];
    }];
    
    NSError *error ;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:result options:NSJSONWritingPrettyPrinted error:&error];
    if (error) {
        NSLog(@"error occour %@", error);
    }
    
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonString;
}

#pragma mark - EditPhotoMarkViewControllerDelegate
-(void)didFinishEditMark:(SNSMarkModel *)data{
    for (UIView *subView in self.markAndImageContainer.subviews) {
        if ([subView isKindOfClass:[SNSMarkLabelView class]]) {
            SNSMarkLabelView *markView = (SNSMarkLabelView *)subView;
            if ([markView.data isEqual:data]) {
                [markView removeFromSuperview];
                SNSMarkLabelView *newMark = [[SNSMarkLabelView alloc]initWithDataModel:data];
                newMark.delegate = self;
                [self.markAndImageContainer addSubview:newMark];
            }
        }
    }
}
-(void)didFinishAddMark:(SNSMarkModel *)data{
    [self addMarkView:data];
}

#pragma mark - SNSMarkLabelViewDelegate
-(void)didTouchedLabel:(SNSMarkLabelView *)labelView{
    NSLog(@"touche mark label");
    __weak id<UIActionSheetDelegate> delegate = self;
    UIActionSheet *actionSheet =[[UIActionSheet alloc]initWithTitle:nil delegate:delegate cancelButtonTitle:@"取消" destructiveButtonTitle:@"翻转" otherButtonTitles:@"删除", nil];
    
    currentMarkLabelView = labelView;
    
    [actionSheet showInView:self.view];
    
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:
            [currentMarkLabelView flipMark];
            break;
        case 1:
            [self.markViewArray removeObject:currentMarkLabelView];
            [currentMarkLabelView removeFromSuperview];
            break;
    }
}
@end
